#include "support_common.h"
#include "common.h"

// Polls DIP switches 3, and 4 to see what the delay should be set to. Returns the delay in ms.
static int dipsw_delay_poll()
{
	if(uc_dipsw_get_state(3) == 1)
	{
		if(uc_dipsw_get_state(4) == 1)
			return 550;
		else
			return 450;
	}
	else
	{
		if(uc_dipsw_get_state(4) == 1)
			return 350;
		else
			return 250;
	}
}

// Polls DIP switch 2 to see if the program should be reversed because it has been moved
// to the Off position or if the program should go back to its original direction because it has been
// moved to the On position. 
static int dipsw_onoff_poll()
{
	return uc_dipsw_get_state(2);
}

// Flash the LED's in the proper sequence per the project requirements.
static void flash_led_sequence(int p_delay)
{
	int direction = dipsw_onoff_poll();
	int i;
	for(i=1; i <= 4; i++)
	{
		// Turn LED ON
		uc_led_on( (direction == 1) ? 5-i: i );
		dtim0_delay(p_delay);
		
		// Turn LED OFF
		uc_led_off( (direction == 1) ? 5-i: i );
		dtim0_delay(p_delay);
		
		if(direction != dipsw_onoff_poll())
		{
			i = 4 - i;
			direction = !direction;
		}
	}
}

// Calls uc_dipsw_init() to initialize the DIP switch, uc_led_init() to initialize the LED's,
// and dtim0_init() to initialize DTIM0.
static void init()
{
	uc_dipsw_init();
	uc_led_init();
	dtim0_init();
}

// Calls init() to initialize the hardware. Then drops into an infinite loop calling
// flash_led_sequence() forever.
int main()
{
	init();
	uc_led_all_off();
	while (1)
	{
		flash_led_sequence( dipsw_delay_poll() );
	}
	
	return 0;
}